/*  
 *  Copyright (c) 2008 Adrian Necimal <necimal@gmail.com>
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://app/jsmodules/sbProperties.jsm");

var gUnescapeHTML = Cc["@mozilla.org/feed-unescapehtml;1"].getService(Ci.nsIScriptableUnescapeHTML);
var gXPath = Cc["@mozilla.org/dom/xpath-evaluator;1"].createInstance(Ci.nsIDOMXPathEvaluator);

function SSLastfmBio() {
  this.wrappedJSObject = this;
};

SSLastfmBio.prototype = {
  classDescription: "SuperSidebar Last.fm Bio Provider",
  classID: Components.ID("{9194FCA4-F604-482f-8434-9B6B8061BF85}"),
  contractID: "@necimal.com/supersidebar/lastfmbio;1",
  QueryInterface: XPCOMUtils.generateQI([]),
  providerID: "ssbioprovider",
  providerTitle: "Biography"
}

// the provider should look for content about the given mediaItem, and then notify the contentListener
SSLastfmBio.prototype.getContent = function(mediaItem, contentListener) {
  // make a request to Last.fm asynchronously
  var artistName = mediaItem.getProperty(SBProperties.artistName);
  var bioRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
  bioRequest.requestUri = "http://ws.audioscrobbler.com/2.0/artist/info.xml?artist=" + escape(artistName);
  bioRequest.ssProvider = this;
  bioRequest.open("GET", bioRequest.requestUri, true);
  bioRequest.onreadystatechange = function(ev) {
    if (this.readyState != 4) { return; }
    if (this.status == 200) {
      // create a node to hold our biography
      var document = Cc["@mozilla.org/xul/xul-document;1"].createInstance(Ci.nsIDOMXULDocument);
      var result = document.createElement("description");
      
      // get the artist biography from the response
      result.textContent = gXPath.evaluate("/artist/bio/summary", this.responseXML, null, 2, null).stringValue;
      
      // return the result by notifying the contentListener
      contentListener.updateContent(this.ssProvider, result);
    }
  };
  bioRequest.send(null);
}

function NSGetModule(compMgr, fileSpec) {
  return XPCOMUtils.generateModule([SSLastfmBio]);
}
